package pl.streamsoft.currencyApp.model;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

import org.hibernate.annotations.Filter;
import org.hibernate.annotations.ParamDef;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.annotations.FetchProfile;
import org.hibernate.annotations.FilterDef;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;

@Entity
@Table(name = "COUNTRIES")
@NamedQueries({
		@NamedQuery(name = "Country.getCountriesByName", query = "from Country where countryName = :countryName"),
		@NamedQuery(name = "Country.getAllCountries", query = "from Country"),
		@NamedQuery(name = "Country.getCountriesByMinValueOfCurrencies", query = "from Country c where size(c.currencies) >= :minValueOfCurrencies") })

@FetchProfile(name = "profile.enable_fjm", fetchOverrides = { @FetchProfile.FetchOverride(entity = Country.class, association = "currencies", mode = FetchMode.JOIN) })

@FilterDef(name="country.currencyLike", parameters=@ParamDef( name="charSequence", type="string" ) )

public class Country {

	@Id
	@GeneratedValue
	@Column(name = "COUNTRY_ID")
	private long countryId;

	@Column(name = "NAME")
	private String countryName;

	@Filter(name = "country.currencyLike", condition="name like = :charSequence")
	
	@ManyToMany
	@Cascade(CascadeType.SAVE_UPDATE)
	@Fetch(FetchMode.JOIN)
	@NotFound(action = NotFoundAction.IGNORE)
	@JoinTable(name = "JOIN_COUNTRY_AND_CURRENCY_INFO", joinColumns = @JoinColumn(name = "COUNTRY_ID"), inverseJoinColumns = @JoinColumn(name = "CURRENCY_INFO_ID"))
	private final Set<CurrencyInfo> currencies = new HashSet<CurrencyInfo>();

	public Country() {
	}

	public Country(String countryName) {
		this.countryName = countryName;
	}

	public String getCountryName() {
		return countryName;
	}

	public boolean addCurrency(Currency value) {
		return currencies.add(value.getCurrencyInfo());
	}

	public Currency[] getCurrencies() {
		return currencies.toArray(new Currency[currencies.size()]);
	}

	public int getCurrencySize() {
		return currencies.size();
	}

	public void changeName(String name) {
		this.countryName = name;
	}

	@Override
	public int hashCode() {
		return countryName.hashCode();
	}

	@Override
	public boolean equals(Object o) {
		return countryName.equals(o);
	}
}
